const router = require('koa-router')()
const fs = require('fs')
const path = require('path')
const imagesPath = path.resolve(__dirname, '../public/images')
const OSS = require('ali-oss')

const client = new OSS({
  // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
  region: 'oss-cn-shanghai',
  // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  accessKeyId: `LTAI5t9KsYSgh9uDEw6HuRtP`,
  accessKeySecret: `jJzLNCN9U38ZhDPmyfnKPhpNSehJn7`,
  // 填写Bucket名称。
  bucket: '2107a-1',
});

router.post('/upload', ctx => {
  // 1. 获取上传的文件
  const { filepath, originalFilename, newFilename, } = ctx.request.files.file
  // 2。 将文件放入public/images
  fs.copyFileSync(filepath, path.join(imagesPath, newFilename + path.extname(originalFilename)))
  // 3. 返回文件 需要时 服务器静态资源路径 
  ctx.body = {
    code: 200,
    data: `http://10.1.125.57:8000/images/` + newFilename + path.extname(originalFilename)
  }
})

router.get('/upload/list', ctx => {
  const list = fs.readdirSync(imagesPath).map(v => {
    return `http://10.1.125.57:8000/images/` + v 
  })

  ctx.body = {
    code: 200,
    data: list
  }
})

router.post('/upload/oss', async ctx => {
  const { filepath, originalFilename, newFilename, } = ctx.request.files.file;

  // 上传到oss
  const resp = await client.put(originalFilename, filepath)

  ctx.body = {
    code: 200,
    data: resp
  }
})

router.get('/upload/oss/list', async ctx => {
  const resp = await client.list();

  ctx.body = {
    code: 200,
    data: resp
  }
})

module.exports = router
